import Room from "../socket/utils/room.ts";
import {Server as SocketIOServer, Socket} from "socket.io";
import useWebRTCSocket from "./webrtcSocket.ts";
import {SOCKET_EVENTS} from "../../constants/socketState.ts";

function defaultSocket(io: SocketIOServer, socket: Socket) {

    const rooms: Map<string, Room> = new Map();
    const roomId = socket.handshake.query.roomId as string;
    const username = socket.handshake.query.username as string;

    if (!roomId) {
        console.error('该客户端没有提供房间号');
        return;
    }

    // 获取房间当前人数
    const getRoomSize = () => io.sockets.adapter.rooms.get(roomId) ? Array.from(io.sockets.adapter.rooms.get(roomId)) : [];

    let roomSize = getRoomSize();

    // 如果房间不存在，则创建房间
    if (!rooms.has(roomId)) {
        rooms.set(roomId, new Room());
    }

    const room = rooms.get(roomId)!;

    // 用户加入处理
    if (roomSize.length < 1000) {
        socket.join(roomId);
        room.addUser(socket.id, username);  // 增加用户到房间
        socket.emit("joined", roomId, socket.id);
        socket.broadcast.to(roomId).emit("otherjoin", roomId, socket.id);

        // 关于webrtc的服务
        useWebRTCSocket(socket, {roomId, io})

        // 更新房间人数
        roomSize = getRoomSize();
        io.to(roomId).emit(SOCKET_EVENTS.ROOM.ROOMINFO, roomSize);
    } else {
        socket.emit("full", roomId, socket.id);
    }

    // 用户离开处理
    const handleLeave = () => {
        room.removeUser(socket.id);
        socket.leave(roomId);

        roomSize = getRoomSize();
        io.to(roomId).emit(SOCKET_EVENTS.ROOM.ROOMINFO, roomSize);

        if (roomSize.length === 0) {
            rooms.delete(roomId);
        }
    };

    socket.on("leave", handleLeave);

    // 处理消息
    socket.on("message", (message: string) => {
        console.log("message", roomId, message);
        socket.broadcast.to(roomId).emit("message", roomId, message);
    });

    // 处理心跳
    socket.on("heartbeat", () => {
        // console.log("Heartbeat received from:", socket.id);
        roomSize = getRoomSize();
        io.to(roomId).emit('roomSize', roomSize);
        socket.emit("heartbeatResponse");
    });

    // 定时器，用于定期更新房间人数
    let timer = setInterval(() => {
        roomSize = getRoomSize();
        io.to(roomId).emit('roomSize', roomSize);
    }, 2000);

    // 处理断开连接
    socket.on("disconnect", () => {
        console.log(`User disconnected: ${socket.id}`);
        handleLeave();
        clearInterval(timer);
    });
}

export default defaultSocket;